package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.ParamMsg;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.service.IUserService;
import com.itheima.util.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户登录规则")
public class UserController {

    @Autowired
    private IUserService userService;

    //注入redis
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;


//    此处创建一个验证码的方法
    @GetMapping("/login")
    @ApiOperation(value = "向用户发送验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone",value = "手机号",required = true )
//            @ApiImplicitParam(name = "session",value = "session",required = false)
    })
    public R<String> userLogin(String phone, HttpSession session){
        log.info("接收前端发送的手机号：{}",phone);
//        调用验证码信息
        String code = String.valueOf(ValidateCodeUtils.generateValidateCode(6));
        log.info("当前的验证码为：{}",code);
//        自定义类，向手机端发送信息
//        ParamMsg.phone(phone,code);

        //将获取的验证码信息替换session，存储到redis中，定义过期时间3分钟
        redisTemplate.opsForValue().set(phone,code,3, TimeUnit.MINUTES);
        return R.success("验证发送成功");
    }

//    此处创建登录
    //请求url地址：/user/login
    //请求方式：POST
    //请求参数：JSON格式数据，使用 User 封装
    //{"phone":"138xxxxxxx","code":"1234"}

    @PostMapping("/login")
    @ApiOperation(value = "用户登录规则")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "map",value = "前端发送的登录信息",required = true)
    })
    public R<User> login(@RequestBody Map map,HttpSession session){
//        从map中获取键值对
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        //根据手机号，从redis中获取验证码信息
        String sysCode = (String) redisTemplate.opsForValue().get(phone);
        if (code.equals(sysCode)){
//            先查询
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User user = userService.getOne(wrapper);
//            如果没有注册，执行注册操作
            if (user==null){
                user = new User();
                user.setPhone(phone);
                user.setName(phone);
                userService.save(user);
            }
//            验证码正确，清空redis验证码信息
            redisTemplate.delete(phone);
//            将用户的ID存储到session中，便于后续的操作使用
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("您输入的验证码有误，请重新输入");
    }

//    创建退出功能
    @PostMapping("/loginout")
    @ApiOperation(value = "用用户退出操作")
    public R<String> loginout(HttpSession session){
//        清除信息
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
